package com.s69.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.s69.ssm.entity.QueryParams;
import com.s69.ssm.entity.Student;
import com.s69.ssm.service.StudentService;
import com.s69.ssm.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/stu")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/list")
    public String list(QueryParams queryParams, Model model, HttpSession session) {
        PageHelper.startPage(queryParams.getPageNo(), queryParams.getPageSize());
        List<Student> list = studentService.list(queryParams);
        PageInfo<Student> pageInfo = PageInfo.of(list);
        model.addAttribute("page", pageInfo);
        // 使用session保存查询条件，方便增删改后回显查询条件
        session.setAttribute("queryParams", queryParams);
        return "list";
    }

    @GetMapping("/update/{id}")
    public String update(@PathVariable Integer id, Model model) {
        model.addAttribute("stu", studentService.get(id));
        return "update";
    }

    @PostMapping("/update")
    public String update(Student student, MultipartFile uploadFile, HttpSession session, RedirectAttributes redirectAttributes) throws IOException {
        String filename = FileUtil.saveFile(uploadFile);
        student.setFaceimg(filename);
        studentService.update(student);
        return back(session, redirectAttributes);
    }

    @GetMapping("/add")
    public String add() {
        return "add";
    }

    @PostMapping("/add")
    public String add(Student student, MultipartFile uploadFile, HttpSession session, RedirectAttributes redirectAttributes) throws IOException {
        String filename = FileUtil.saveFile(uploadFile);
        student.setFaceimg(filename);
        studentService.add(student);
        return back(session, redirectAttributes);
    }

    @GetMapping("/del")
    @ResponseBody
    public boolean del(Integer id) {
        studentService.del(id);
        return true;
    }

    @GetMapping("/upload/{id}")
    public String upload(@PathVariable Integer id, Model model) {
        model.addAttribute("id", id);
        return "upload";
    }

    @PostMapping("/upload")
    public String upload(Student student,
                         MultipartFile idcardPositiveFile,
                         MultipartFile idcardNegativeFile,
                         Model model,
                         HttpSession session, RedirectAttributes redirectAttributes) throws IOException {
        Map<String, List<String>> errors = validateUpload(idcardPositiveFile, idcardNegativeFile);
        if (!errors.isEmpty()) {
            model.addAttribute("errors", errors);
            model.addAttribute("id", student.getId());
            return "upload";
        }
        String idcardPositive = FileUtil.saveFile(idcardPositiveFile);
        String idcardNegative = FileUtil.saveFile(idcardNegativeFile);
        student.setIdcardPositive(idcardPositive);
        student.setIdcardNegative(idcardNegative);
        studentService.updateIdCardFile(student);
        return back(session, redirectAttributes);
    }

    @GetMapping("/exists")
    @ResponseBody
    public boolean exists(String stuno) {
        Student student = studentService.getByStuNo(stuno);
        return student != null;
    }

    @GetMapping("/backToList")
    public String back(HttpSession session, RedirectAttributes redirectAttributes) {
        if (session.getAttribute("queryParams") != null) {
            // 添加重定向参数，回显查询条件
            redirectAttributes.addFlashAttribute("queryParams", session.getAttribute("queryParams"));
        }
        return "redirect:/stu/list";
    }

    private Map<String, List<String>> validateUpload(MultipartFile idcardPositiveFile, MultipartFile idcardNegativeFile) {
        Map<String, List<String>> errors = new HashMap<>();
        List<String> idcardPositiveErrors = new ArrayList<>();
        List<String> idcardNegativeErrors = new ArrayList<>();
        long maxSize = 1024 * 1024;
        List<String> allowList = Arrays.asList("png", "gif", "jpg", "jpeg");
        if (idcardPositiveFile == null || idcardPositiveFile.getSize() == 0) {
            idcardPositiveErrors.add("正面照片不能为空");
        } else {
            if (idcardPositiveFile.getSize() > maxSize) {
                idcardPositiveErrors.add("正面照片超过1M");
            }
            if (!allowList.contains(FileUtil.getFileType(idcardPositiveFile))) {
                idcardPositiveErrors.add("正面照片类型只能是" + allowList);
            }
        }
        if (idcardNegativeFile == null || idcardNegativeFile.getSize() == 0) {
            idcardNegativeErrors.add("反面照片不能为空");
        } else {
            if (idcardNegativeFile.getSize() > maxSize) {
                idcardNegativeErrors.add("反面照片超过1M");
            }
            if (!allowList.contains(FileUtil.getFileType(idcardNegativeFile))) {
                idcardNegativeErrors.add("正面照片类型只能是" + allowList);
            }
        }
        if (!idcardPositiveErrors.isEmpty()) {
            errors.put("idcardPositive", idcardPositiveErrors);
        }
        if (!idcardNegativeErrors.isEmpty()) {
            errors.put("idcardNegative", idcardNegativeErrors);
        }
        return errors;
    }
}
